/**
  ******************************************************************************
  * @file    usart.c
  * @brief   This file provides code for the configuration
  *          of the USART instances.
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "gd32f30x.h"

/* USER CODE BEGIN 0 */
// #include  <errno.h>
// #include  <sys/unistd.h> // STDOUT_FILENO, STDERR_FILENO

void uart0_send_string(uint8_t *str);

/* USER CODE END 0 */


/* USART1 init function */

void USART1_UART_Init(void)
{
#if 1
  	/* Ê¹ÄÜ GPIO Ê±ÖÓ */
    rcu_periph_clock_enable(RCU_GPIOA);

    /* Ê¹ÄÜ uart Ê±ÖÓ */
    rcu_periph_clock_enable(RCU_USART0);

    /* ½«GPIO A9 Òý½Å¸´ÓÃÎª USARTx_Tx */
    gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_9);

    /* ½«GPIO A10 Òý½Å¸´ÓÃÎª USARTx_Rx */
    gpio_init(GPIOA, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_10);

    /* USART È¥³õÊ¼»¯ */
    usart_deinit(USART0);
	//²¨ÌØÂÊÉèÖÃ
    usart_baudrate_set(USART0, 115200U);
	//½ÓÊÜÊ¹ÄÜ
    usart_receive_config(USART0, USART_RECEIVE_ENABLE);
	//·¢ËÍÊ¹ÄÜ
    usart_transmit_config(USART0, USART_TRANSMIT_ENABLE);
	//Ê¹ÄÜ´®¿Ú0
    usart_enable(USART0);

	/* ÖÐ¶ÏÅäÖÃ */
	
	/* Ê¹ÄÜ´®¿ÚÖÐ¶Ï */
    nvic_irq_enable(USART0_IRQn, 0, 0);
	/* Ê¹ÄÜ USART0 ½ÓÊÕÖÐ¶Ï */
    usart_interrupt_enable(USART0, USART_INT_RBNE);
#endif

    uart0_send_string((uint8_t *)"uart init ok...\r\n");
}

void USART1_IRQHandler(void)
{
	if(RESET != usart_interrupt_flag_get(USART0, USART_INT_FLAG_RBNE))
	{
		/* Read one byte from the receive data register */
		//ch = (uint8_t)usart_data_receive(USART0);
	}
}

void uart0_send_byte(uint8_t ch)
{
	usart_data_transmit(USART0, (uint8_t)ch);
    while(RESET == usart_flag_get(USART0, USART_FLAG_TBE));
}

void uart0_send_string(uint8_t *str)
{
	uint8_t *p = str;
	while(*p)
	{
		uart0_send_byte(*p);
		p++;
	}
}

void uart0_send_data(uint8_t *data, int len)
{
	int i;
	for(i = 0; i < len; i++)
	{
		uart0_send_byte(data[i]);
	}
}


int __io_putchar(int ch)
{
    usart_data_transmit(USART0, (uint8_t)ch);
    while(RESET == usart_flag_get(USART0, USART_FLAG_TBE));

    return ch;
}

